<template>
  <div class="login-box">
    <el-form
      :rules="formRules"
      :model="formData"
      ref="formRef"
    >
      <el-form-item prop="username">
        <!-- 
          prefix-icon 是在输入框前面添加字体图标
          show-password 是显示小眼睛
        -->
        <el-input
          placeholder="请填写用户名"
          prefix-icon="User"
          v-model="formData.username"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          placeholder="请填写密码"
          prefix-icon="Lock"
          type="password"
          show-password
          v-model="formData.password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="onLogin"
        >登 入</el-button>
        <el-button @click="onReset">重 置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
  import { reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus'
  // 4个绑定： form 绑定校验数组和存储数组 / item 绑定校验对象 / input 是绑定存储对象
  // 校验规则
  const formRules = {
    // 用户名
    username: [
      { min: 5, max: 10, message: '长度必须是5到10', trigger: 'blur' },
      { required: true, message: '请输入内容', trigger: 'blur' },
    ],
    // 密码
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      { min: 6, max: 15, message: '密码长度需在6-15之间', trigger: 'blur' }
    ]
  }

  // 存储对象
  const formData = reactive({
    username: '',
    password: ''
  })

  // 表单对象
  const formRef = ref(null)

  // 登入
  const onLogin = () => {
    formRef.value.validate((valid) => {
      if (!valid) return ElMessage({
        showClose: true,
        message: '输入有误，请重新核对',
        type: 'error'
      })
      console.log('ok');
      // ...
    })
  }

  const onReset = () => {
    if (confirm('您确认要重置吗？')) formRef.value.resetFields()
  }
</script>

<style lang="scss">
  * {
    margin: 0;
  }

  body {
    background-color: #ccc;
  }

  .login-box {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;

    .el-form {
      width: 400px;
      padding: 40px 50px;
      background-color: #fff;

      .el-form-item {
        max-width: 20xp;
      }

      .el-input {
        height: 40px;
      }
    }
  }
</style>